
/**
 * 解析路由规则
 * @param {路由规则} routes 
 * @param {路径列表} pathList 
 * @param {路径映射} pathMap 
 */
//  routes: [{
//     path: '/',
//     component: HOME,
// }, {
//     path: '/Login',
//     component: LOGIN,
// }, {
//     path: '/a',
//     component: A,
//     children: [
//         {
//             path: '/b',
//             component: B
//         }
//     ]
// }]
// pathList:['/','/login','/a','/a/b']
export function createRouterMap(routes, oldPathList, oldPathMap) {

    const pathList = oldPathList || [];

    const pathMap = oldPathMap || Object.create(null);

    // 循环路由规则，调用增加路由
    routes.forEach(route => {
        addRouteRecord(pathList, pathMap, route);
    });

    console.log(pathList);
    console.log(pathMap);
    return {
        pathList,
        pathMap
    }
}

/**
 * 添加路由对象
 * @param {路由列表} pathList 
 * @param {映射对象，路径和组件的映射} pathMap 
 * @param {待加入的路由对象} route 
 * @param {标记一下是否有父节点} parentRecord 
 */
function addRouteRecord(pathList, pathMap, route, parentRecord) {
    // 如果当前解析的子路由，则前面需要加上父路由的前缀
    const path = parentRecord ? `${parentRecord.path}/${route.path}` : route.path;
    const record = {
        path,
        component: route.component,
        parent: parentRecord
    }

    // 已经放过了就不再往里存了
    if (!pathMap[path]) {
        pathList.push(path);
        pathMap[path] = record;
    }

    // 判断当前节点是否有子节点
    if (route.children) {
        route.children.forEach(child => {
            // 有孩子，递归调用
            addRouteRecord(pathList, pathMap, child, record);
        })
    }
}

